package interview.leetcode;
/**
* Created by 44931 on 2017/9/1.
*/
public class Solution2 {
int index = -1;
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
String Serialize(TreeNode root, StringBuffer stringBuffer) {
if (null == root) {
return String.valueOf(stringBuffer.append("#,"));
}
stringBuffer.append(String.valueOf(root.val)+",");
Serialize(root.left, stringBuffer);
Serialize(root.right, stringBuffer);
return String.valueOf(stringBuffer);
}
String Serialize(TreeNode root) {
StringBuffer stringBuffer = new StringBuffer();
return Serialize(root, stringBuffer);
}
TreeNode Deserialize(String str) {
index++;
int len = str.length();
if(index >= len){
return null;
}
String[] strr = str.split(",");
TreeNode node = null;
if(!strr[index].equals("#")){
node = new TreeNode(Integer.valueOf(strr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
TreeNode Deserialize(String[] temp) {
index++;
if (temp.length < 1 || index < 0 || temp.length < index || temp[index].equals("#")) {
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(temp[index]));
root.left = Deserialize(temp);
root.right = Deserialize(temp);
return root;
}
public static void frontSearch(TreeNode node) {
if (node == null) {
return;
}
System.out.println(node.val);
frontSearch(node.left);
frontSearch(node.right);
}
public static void main(String[] args) {
Solution2 solution2 = new Solution2();
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
TreeNode n6 = new TreeNode(6);
TreeNode n7 = new TreeNode(7);
TreeNode n8 = new TreeNode(8);
TreeNode n9 = new TreeNode(9);
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
n4.left = n8;
n4.right = n9;
System.out.println(solution2.Serialize(n1));
frontSearch(solution2.Deserialize(solution2.Serialize(n1)));
}
}